<template>
  <div class="mobile-order-recall-list">
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <el-select v-model="recallStatus" placeholder="召回状态" size="mini" @change="handleStatusChange" style="width: 100%;">
        <el-option label="所有状态" value=""></el-option>
        <el-option label="召回中" value="1"></el-option>
        <el-option label="召回成功" value="2"></el-option>
        <el-option label="召回失败" value="3"></el-option>
      </el-select>

      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索订单号/邮箱"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          size="mini">
        </el-input>
      </div>

      <div class="action-buttons">
        <el-button type="primary" size="mini" @click="batchRecall" :disabled="selectedItems.length === 0">
          批量召回
        </el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list-container">
      <div v-if="loading && list.length === 0" class="loading-placeholder">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>

      <div v-if="list.length === 0 && !loading" class="empty-placeholder">
        <i class="el-icon-document"></i>
        <span>暂无订单数据</span>
      </div>

      <div v-for="(item, index) in list" :key="index" class="order-item">
        <div class="order-header">
          <div class="checkbox-wrapper">
            <el-checkbox v-model="item.selected" @change="handleItemSelect(item)"></el-checkbox>
          </div>
          <div class="order-number" @click="handleDetail(item.id)">订单号：{{ item.orderNumber }}</div>
          <div class="order-status" :class="getStatusClass(item.recallStatusText)">{{ item.recallStatusText }}</div>
        </div>

        <div class="order-info">
          <div class="info-row">
            <span class="label">下单邮箱：</span>
            <span class="value">{{ item.email }}</span>
          </div>
          <div class="info-row">
            <span class="label">订单金额：</span>
            <span class="value">{{ formatCurrency(item.payAmount, item.currencySymbol) }}</span>
          </div>
          <div class="info-row">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDate(item.createDate) }}</span>
          </div>
          <div class="info-row">
            <span class="label">商品数量：</span>
            <span class="value">{{ item.totalItemNum }}</span>
          </div>
          <div class="info-row">
            <span class="label">召回次数：</span>
            <span class="value">{{ item.recallNum }}</span>
          </div>
        </div>

        <div class="order-actions">
          <el-button v-if="item.recallStatus === 3" size="mini" type="primary" @click="handleReCall(item.id)">
            召回
          </el-button>
        </div>
      </div>

      <div v-if="loading && list.length > 0" class="loading-more">
        <i class="el-icon-loading"></i>
        <span>加载更多...</span>
      </div>

      <div v-if="noMore && list.length > 0" class="no-more">
        已加载全部数据
      </div>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formParams.page"
          :page-sizes="[20, 30, 50]"
          :page-size="formParams.pageSize"
          layout="total, prev, pager, next"
          :small="true"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 召回对话框 -->
    <el-dialog title="发送邮件" :visible.sync="recallDialogVisible" width="90%" center>
      <el-form label-width="100px">
        <el-form-item label="选择优惠码">
          <el-select v-model="code" placeholder="优惠码" clearable style="width: 100%;">
            <el-option v-for="item in couponCodeList" :value="item.couponCodeId" :label="item.activityName"
                      :key="item.activityName"></el-option>
          </el-select>
          <div class="link-wrapper">
            <router-link :to="{name: 'coupon-codes-add'}" class="link-btn">
              新建优惠码
            </router-link>
          </div>
        </el-form-item>
        <el-form-item label="邮件模板">
          <el-select v-model="marketingParentId" placeholder="邮件模板" @change="initEmailModelsList(marketingParentId)" style="width: 100%; margin-bottom: 10px;">
            <el-option v-for="item in marketingParentList" :value="item.id" :label="item.noticeName"
                      :key="item.id"></el-option>
          </el-select>
          <el-select v-model="marketingId" placeholder="邮件模板" style="width: 100%;">
            <el-option v-for="item in marketingList" :value="item.id" :label="item.emailModelName"
                      :key="item.id"></el-option>
          </el-select>
          <div class="link-wrapper">
            <span class="link-btn" @click="goGoodsDetail('inform-template-list', 3, marketingParentId, 'marketing_activity')">
              模板管理
            </span>
            <span class="link-btn" @click="goGoodsDetail('inform-template-add', 3, marketingParentId, 'marketing_activity')">
              新增邮件模板
            </span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handlePrew(marketingId)">预览</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recallDialogVisible = false; code=null">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="postRecall">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量召回对话框 -->
    <el-dialog title="批量召回" :visible.sync="batchRecallDialogVisible" width="90%" center>
      <el-form label-width="100px">
        <el-form-item label="选择优惠码">
          <el-select v-model="code" placeholder="优惠码" clearable style="width: 100%;">
            <el-option v-for="item in couponCodeList" :value="item.couponCodeId" :label="item.activityName"
                      :key="item.activityName"></el-option>
          </el-select>
          <div class="link-wrapper">
            <router-link :to="{name: 'coupon-codes-add'}" class="link-btn">
              新建优惠码
            </router-link>
          </div>
        </el-form-item>
        <el-form-item label="邮件模板">
          <el-select v-model="marketingParentId" placeholder="邮件模板" @change="initEmailModelsList(marketingParentId)" style="width: 100%; margin-bottom: 10px;">
            <el-option v-for="item in marketingParentList" :value="item.id" :label="item.noticeName"
                      :key="item.id"></el-option>
          </el-select>
          <el-select v-model="marketingId" placeholder="邮件模板" style="width: 100%;">
            <el-option v-for="item in marketingList" :value="item.id" :label="item.emailModelName"
                      :key="item.id"></el-option>
          </el-select>
          <div class="link-wrapper">
            <span class="link-btn" @click="goGoodsDetail('inform-template-list', 3, marketingParentId, 'marketing_activity')">
              模板管理
            </span>
            <span class="link-btn" @click="goGoodsDetail('inform-template-add', 3, marketingParentId, 'marketing_activity')">
              新增邮件模板
            </span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handlePrew(marketingId)">预览</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchRecallDialogVisible = false; code=null">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="postBatchRecall">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog :visible.sync="isOpen" title="" :append-to-body="true" class="custom-url" @close="isOpen=false">
      <iframe :srcdoc="showTemplateContent" frameborder="0" width="100%" height="600px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderRecallPage, orderRecall } from '@/api/order';
import { mapGetters } from 'vuex';
import { getCouponCodeList } from '@/api/marketing';
import { getEmailModelsList, getMarketingList } from '@/api/inform';
import {currency} from '@/utils/filters';

export default {
    name: 'MobileOrderRecallList',
    props: {
        siteId: {
            type: [String, Number],
            required: true
        }
    },
    data () {
        return {
            list: [],
            loading: false,
            page: 1,
            pageSize: 10,
            total: 0,
            noMore: false,
            recallStatus: '',
            searchText: '',
            dateRange: [],
            pickerOptions: {
                firstDayOfWeek: 1,
                shortcuts: [{
                    text: '最近一周',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 1);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 3);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            params: {
                recallStatus: '',
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: '',
                page: 1,
                pageSize: 20
            },
            selectedItems: [],
            recallDialogVisible: false,
            batchRecallDialogVisible: false,
            code: null,
            marketingParentId: '',
            marketingId: '',
            submitLoading: false,
            couponCodeList: [],
            marketingParentList: [],
            marketingList: [],
            recallId: '',
            showTemplateContent: '',
            isOpen: false,
            formParams: {
                siteId: this.siteId,
                page: 1,
                pageSize: 10
            }
        };
    },
    computed: {
        ...mapGetters(['timeZone'])
    },
    created () {
        this.fetchData();
        this.initCouponCode();
    },
    methods: {
        fetchData () {
            this.loading = true;

            // 处理日期范围
            if (this.dateRange && this.dateRange.length === 2) {
                this.formParams.startTime = this.getSiteTimeZoneStartTime(this.dateRange[0]);
                this.formParams.endTime = this.getSiteTimeZoneEndTime(this.dateRange[1]);
            } else {
                this.formParams.startTime = '';
                this.formParams.endTime = '';
            }

            getOrderRecallPage(this.formParams).then(res => {
                const records = res.records || [];

                // 添加选择状态
                records.forEach(item => {
                    item.selected = false;
                });
                this.list = res.records || [];
                this.total = res.totalElements || 0;
                this.noMore = this.list.length >= this.total;
                this.loading = false;
            }).catch(() => {
                this.loading = false;
            });
        },
        handleStatusChange () {
            this.formParams.page = 1;
            this.params.recallStatus = this.recallStatus;
            this.list = [];
            this.selectedItems = [];
            this.noMore = false;
            this.fetchData();
        },

        handleSearch () {
            this.formParams.page = 1;
            this.list = [];
            this.selectedItems = [];

            // 重置搜索参数
            this.params.orderNumber = '';
            this.params.email = '';

            this.fetchData();
        },

        handleItemSelect (item) {
            if (item.selected) {
                this.selectedItems.push(item);
            } else {
                const index = this.selectedItems.findIndex(i => i.id === item.id);
                if (index !== -1) {
                    this.selectedItems.splice(index, 1);
                }
            }
        },

        handleDetail (id) {
            this.$router.push({ name: 'order-detail', params: { id }, query: { type: 'recall' } });
        },

        // 订单召回
        handleReCall (id) {
            this.recallDialogVisible = true;
            this.initMarketingList();
            this.recallId = id;
        },

        // 批量召回
        batchRecall () {
            if (!this.selectedItems.length) {
                return this.$message.warning('请先选择需要召回的订单！');
            }

            if (this.selectedItems.every(s => s.recallStatus !== 3)) {
                return this.$message.warning('请选择召回失败的订单！');
            }

            this.batchRecallDialogVisible = true;
            this.initMarketingList();
        },

        postRecall () {
            this.submitLoading = true;
            orderRecall({
                orderIds: this.recallId.toString(),
                siteId: this.siteId,
                couponCodeId: this.code,
                emailModelId: this.marketingId
            }).then(res => {
                this.submitLoading = false;
                if (res.code === '200') {
                    this.$message.success('发送成功');
                    this.code = null;
                    this.recallDialogVisible = false;

                    // 刷新数据
                    this.page = 1;
                    this.list = [];
                    this.selectedItems = [];
                    this.noMore = false;
                    this.fetchData();
                }
            }).catch(() => {
                this.submitLoading = false;
                this.recallDialogVisible = false;
            });
        },

        postBatchRecall () {
            this.submitLoading = true;
            orderRecall({
                orderIds: this.selectedItems.map(s => s.id).join(','),
                siteId: this.siteId,
                couponCodeId: this.code,
                emailModelId: this.marketingId
            }).then(res => {
                this.submitLoading = false;
                if (res.code === '200') {
                    this.$message.success('发送成功');
                    this.code = null;
                    this.batchRecallDialogVisible = false;

                    // 刷新数据
                    this.page = 1;
                    this.list = [];
                    this.selectedItems = [];
                    this.noMore = false;
                    this.fetchData();
                }
            }).catch(() => {
                this.submitLoading = false;
                this.batchRecallDialogVisible = false;
            });
        },

        initCouponCode () {
            getCouponCodeList({
                siteId: this.siteId
            }).then(res => {
                this.couponCodeList = res.data;
            });
        },

        initMarketingList () {
            getMarketingList({ siteId: this.siteId }).then(res => {
                this.marketingParentList = res.data;
                this.marketingParentId = this.marketingParentList.find(s => s.noticeDetailType === '0').id;
                this.initEmailModelsList(this.marketingParentId);
            });
        },

        initEmailModelsList (id) {
            getEmailModelsList({ siteId: this.siteId, noticeId: id, emailType: 3 }).then(res => {
                this.marketingList = res.data;
                const codeId = this.marketingParentList.find(s => s.id === id).promotionCodeId || '';
                const codeInId = this.couponCodeList.find(s => s.couponCodeId === codeId);
                this.code = (codeInId && codeInId.couponCodeId) || '';
                this.marketingId = this.marketingList.find(s => s.emailDefaultState === '0').id;
            });
        },

        handlePrew (id) {
            this.isOpen = true;
            this.showTemplateContent = '';
            setTimeout(() => {
                this.showTemplateContent = this.marketingList.find(s => s.id === id).emailModelSourceCode;
            });
        },

        goGoodsDetail (name = 'inform-template-list', emailType, noticeId, tag) {
            let routeData = this.$router.resolve({
                name,
                query: { ...this.$route.query, emailType, noticeId, tag }
            });
            window.open(routeData.href, '_blank');
        },

        formatCurrency (amount, symbol = '$') {
            if (!amount) { return ''; }
            return currency(amount, symbol || '$');
        },

        formatDate (timestamp) {
            if (!timestamp) { return ''; }

            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },

        getStatusClass (status) {
            const statusMap = {
                '召回中': 'status-processing',
                '召回成功': 'status-success',
                '召回失败': 'status-failed'
            };
            return statusMap[status] || '';
        },

        getSiteTimeZoneStartTime (startTime) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },

        getSiteTimeZoneEndTime (endTime) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },

        handleSizeChange (val) {
            this.formParams.pageSize = val;
            this.fetchData();
        },

        handleCurrentChange (val) {
            this.formParams.page = val;
            this.fetchData();
        },

        resetForm () {
            this.formParams = {
                siteId: this.siteId,
                page: 1,
                pageSize: 10
            };
            this.dateRange = [];
            this.fetchData();
        }
    }
};
</script>

<style lang="scss" scoped>
.mobile-order-recall-list {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .filter-bar {
    margin-bottom: 15px;

    .search-box {
      margin-top: 10px;
    }

    .action-buttons {
      margin-top: 10px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .filter-form {
    margin-bottom: 15px;
  }

  .order-list-container {
    flex: 1;
    overflow-y: auto;

    .loading-placeholder, .empty-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 200px;
      color: #909399;

      i {
        font-size: 32px;
        margin-bottom: 10px;
      }
    }

    .order-item {
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 15px;
      padding: 15px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

      .order-header {
        display: flex;
        align-items: center;
        padding-bottom: 10px;
        border-bottom: 1px solid #f0f0f0;

        .checkbox-wrapper {
          margin-right: 10px;
        }

        .order-number {
          flex: 1;
          font-weight: bold;
          color: #1A89FF;
        }

        .order-status {
          font-size: 13px;
          padding: 2px 8px;
          border-radius: 10px;

          &.status-processing {
            background-color: #e6f7ff;
            color: #1890ff;
          }

          &.status-success {
            background-color: #f0f9eb;
            color: #67c23a;
          }

          &.status-failed {
            background-color: #fef0f0;
            color: #f56c6c;
          }
        }
      }

      .order-info {
        padding: 10px 0;

        .info-row {
          display: flex;
          margin-bottom: 8px;
          font-size: 13px;

          .label {
            color: #909399;
            width: 80px;
            flex-shrink: 0;
          }

          .value {
            color: #303133;
            flex: 1;
            word-break: break-all;
          }
        }
      }

      .order-actions {
        display: flex;
        justify-content: flex-end;
        padding-top: 10px;
        border-top: 1px solid #f0f0f0;
      }
    }

    .loading-more, .no-more {
      text-align: center;
      color: #909399;
      padding: 15px 0;
      font-size: 13px;

      i {
        margin-right: 5px;
      }
    }
  }

  .link-wrapper {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;

    .link-btn {
      color: #1f7df8;
      margin-right: 15px;
      margin-bottom: 5px;
      cursor: pointer;
    }
  }

  .pagination-container {
    text-align: center;
    margin-top: 20px;
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.custom-url {
  .el-dialog__body {
    padding: 0;
  }
}

@media screen and (max-width: 768px) {
  .mobile-order-recall-list {
    .pagination-container {
      .el-pagination {
        white-space: normal;

        .el-pagination__sizes {
          margin-top: 10px;
        }
      }
    }
  }
}
</style>
